import 'package:flutter/material.dart';

void main() {
  runApp(const ComparableDemoApp());
}

class ComparableDemoApp extends StatelessWidget {
  const ComparableDemoApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Dart Comparable 接口演示',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: const ComparableDemoScreen(),
    );
  }
}

class ComparableDemoScreen extends StatefulWidget {
  const ComparableDemoScreen({super.key});

  @override
  State<ComparableDemoScreen> createState() => _ComparableDemoScreenState();
}

class _ComparableDemoScreenState extends State<ComparableDemoScreen> {
  String _output = '';
  final ScrollController _scrollController = ScrollController();

  // 比较两个 Person 对象并显示结果
  void _comparePersons() {
    _clearOutput();

    // 创建两个 Person 实例
    final alice = Person('Alice', 30);
    final bob = Person('Bob', 25);

    // 比较对象
    _log('比较 ${alice.name} 和 ${bob.name}:');
    _log('${alice.name} 比 ${bob.name} 大: ${alice.compareTo(bob)}');
    _log('${bob.name} 比 ${alice.name} 小: ${bob.compareTo(alice)}');

    final charlie = Person('Charlie', 30);
    _log('\n比较 ${alice.name} 和 ${charlie.name}:');
    _log('${alice.name} 和 ${charlie.name} 相等: ${alice.compareTo(charlie)}');

    // 演示排序
    _log('\n排序演示:');
    List<Person> people = [alice, bob, charlie];
    people.sort();
    _log('排序后: ${people.map((p) => p.name).join(" < ")}');
  }

  // 生成随机 Person 对象进行比较
  void _compareRandomPersons() {
    _clearOutput();

    final random1 = Person('随机用户1', _generateRandomAge());
    final random2 = Person('随机用户2', _generateRandomAge());

    _log('生成随机用户:');
    _log('${random1.name}: ${random1.age} 岁');
    _log('${random2.name}: ${random2.age} 岁');

    final result = random1.compareTo(random2);
    if (result > 0) {
      _log('\n${random1.name} 比 ${random2.name} 大');
    } else if (result < 0) {
      _log('\n${random1.name} 比 ${random2.name} 小');
    } else {
      _log('\n${random1.name} 和 ${random2.name} 年龄相同');
    }
  }

  // 辅助方法
  void _log(String message) {
    setState(() {
      _output += '$message\n';
      _scrollController.animateTo(
        _scrollController.position.maxScrollExtent,
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeOut,
      );
    });
  }

  void _clearOutput() {
    setState(() {
      _output = '';
    });
  }

  int _generateRandomAge() {
    return 18 + (DateTime.now().millisecond % 60); // 生成18-77之间的随机年龄
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Dart Comparable 接口演示'),
        centerTitle: true,
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // 控制按钮
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                ElevatedButton(
                  onPressed: _comparePersons,
                  child: const Text('固定比较示例'),
                ),
                ElevatedButton(
                  onPressed: _compareRandomPersons,
                  child: const Text('随机比较示例'),
                ),
              ],
            ),

            const SizedBox(height: 16),

            // 输出区域
            Expanded(
              child: Container(
                decoration: BoxDecoration(
                  border: Border.all(color: Colors.grey.shade300),
                  borderRadius: BorderRadius.circular(8),
                  color: Colors.grey.shade50,
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    Container(
                      padding: const EdgeInsets.all(8),
                      color: Colors.grey.shade200,
                      child: const Text(
                        '比较结果',
                        style: TextStyle(fontWeight: FontWeight.bold),
                      ),
                    ),
                    Expanded(
                      child: SingleChildScrollView(
                        controller: _scrollController,
                        padding: const EdgeInsets.all(12),
                        child: SelectableText(
                          _output.isEmpty ? '点击按钮进行比较...' : _output,
                          style: const TextStyle(
                            fontFamily: 'monospace',
                            fontSize: 14,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),

            const SizedBox(height: 16),

            // 说明文本
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: Colors.blue.shade50,
                borderRadius: BorderRadius.circular(8),
              ),
              child: const Text(
                'Comparable 接口说明:\n'
                '1. compareTo 返回负数表示当前对象小于另一个对象\n'
                '2. 返回零表示两个对象相等\n'
                '3. 返回正数表示当前对象大于另一个对象\n'
                '4. 常用于排序和比较操作',
                style: TextStyle(fontSize: 14),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class Person implements Comparable<Person> {
  final String name;
  final int age;

  Person(this.name, this.age);

  @override
  int compareTo(Person other) {
    // 按年龄比较大小
    return age - other.age;
  }

  @override
  String toString() => '$name (年龄: $age)';
}
